﻿#include "BackTestOperator.h"
#include "PublicMacros.h"
#include <QFile>
#include <QDir>
#include "MarketService.h"
#include "FileOperator.h"
//#include "MarketRecover.h"
#include "Tools.h"
#include "SymbolDetail.h"
#include "MarketDataStream.h"
#include "CTPTime.h"
#include "KItemGenerator.h"

BackTestOperator::BackTestOperator(MetricsDataGather *pGather)
	: Trader(pGather)
{
	setTradeHandle(&m_tradeModel);
}

BackTestOperator::~BackTestOperator()
{
}

void BackTestOperator::BackTest(time_t circleEndDt, time_t orderEndDt)
{
	std::list<std::string> symbolList;
	SymbolPackage::GetTheLastMainSymbolList(symbolList, circleEndDt);
	SymbolPackage::OrderSymbolReaderWriter orderSymbols;
	orderSymbols.GetSymbolList(symbolList);

	std::set<std::string> symbolsSet;
	for (std::list<std::string>::iterator it = symbolList.begin(); it != symbolList.end(); ++it)
	{
		symbolsSet.insert(*it);
	}
	for (std::set<std::string>::iterator it = symbolsSet.begin(); it != symbolsSet.end(); ++it)
	{
		BackTest(*it, circleEndDt, orderEndDt);
	}
}

void BackTestOperator::BackTest(const std::string &pSymbolName, time_t circleEndDt, time_t orderEndDt)
{
	std::string dy1 = Tools::DateTimeStamp2Str(circleEndDt);
	std::string dy2 = Tools::DateTimeStamp2Str(orderEndDt);
	InitSymbol(pSymbolName, circleEndDt);
	// 复盘操作
	// 取今天和明天的时间
	std::vector<std::string> pDays;
	CTPTm::DateRangeToStringList(circleEndDt, orderEndDt, pDays);
	MDIO::Price priceRecover;
	std::deque<MData::PriceItem> prices;
	for (int i = 0; i < pDays.size(); ++i)
	{
		priceRecover.GetAllPrice(pDays.at(i), pSymbolName, prices);
	}
	time_t lastKItemGenTime;
	KGen::KItemGenerator kGenerator;
	for (std::deque<MData::PriceItem>::iterator it = prices.begin(); it != prices.end(); ++it)
	{
		std::string priceStr = Tools::DateTimeStamp2Str(it->UpdateTime);
		if (it->UpdateTime < circleEndDt)
		{
			continue;
		}
		if (it->UpdateTime > orderEndDt)
		{
			break;
		}
		
		MData::KLineItem lastKItem;
		kGenerator.PushNewPrice(*it, lastKItem);
		// 在这里保存分钟K线
		if (lastKItem.UpdateTime > 0)
		{
			lastKItemGenTime = lastKItem.UpdateTime;
		}
		OnDealMarket(pSymbolName, lastKItemGenTime, *it);
	}
}

void BackTestOperator::InsertCTPOrder(const TD::OrderOption &pOption, TD::OrderBackFunc pFunc)
{
	
}